/*****
 * BEGIN LICENSE BLOCK ***** Version: MPL 1.1
 * 
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations under
 * the License.
 * 
 * The Original Code is BzStats.
 * 
 * The Initial Developer of the Original Code is Michel de Bree (youth). Portions created by the Initial
 * Developer are Copyright (C) 2005 the Initial Developer. All Rights Reserved.
 * 
 * Contributor(s):
 * 
 ***** END LICENSE BLOCK
 *****/

package bzstats;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import bzstats.event.GameEvent;
import bzstats.event.KillEvent;

/**
 * @author youth
 * 
 */
public class DatabaseLogger {

	private static final int UNDEFINED = -1;
	private final Connection connection;

	public DatabaseLogger() throws ClassNotFoundException, SQLException {
		Class.forName("org.sqlite.JDBC");
		connection = DriverManager.getConnection("jdbc:sqlite:yabz.db");
	}

	public void log(GameEvent event) {
		if (event instanceof KillEvent) {

		}
	}

	public int getPlayer(String playerName) throws SQLException {
		Statement stmt = connection.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT id FROM players WHERE name ='" + playerName + "'");
		if (rs.next()) {
			return rs.getInt(1);
		}
		return UNDEFINED;
	}

	public int addPlayer(String playerName) throws SQLException {
		Statement stmt = connection.createStatement();
		stmt.execute("INSERT INTO players(name) VALUES ('" + playerName + "')");
		ResultSet generatedKeys = stmt.getGeneratedKeys();
		generatedKeys.next();
		return generatedKeys.getInt(1);
	}
}